Python socket.error: [Errno 98] Address the reason and solution for already in use

  • 2020-04-02 14:00:48
  • OfStack

A brief analysis of the reasons

Writing a Python with html5 Websocket instance today, the rerun script always indicates that the address already exists and is being used! Query the relevant documents to know that in socket programming, when the client side to the server side to send a message, closed the connection, then if you immediately run the server side program, will prompt this error:


socket.error: [Errno 98] Address already in use

This is because in the four handshakes of TCP/IP termination, when the last ACK reply is sent, there is a waiting time of 2MSL. MSL refers to the maximum time a fragment can live in the network, which is generally 30 seconds, so it can be reconnected after 60 seconds!
Why wait for 2MSL? This is because after the last ACK reply is sent, the sender cannot confirm whether the ACK is normally received by the other end. If the other end does not receive the ACK reply, the FIN fragment will be sent again after 1MSL. So the sender waits for 2MSL, which is exactly the time it sends an ACK reply and the other party sends the FIN fragment. If the other party does not receive the FIN fragment again within this time, the sender assumes that the other party has received the ACK reply normally, and then it will normally close the connection!

Two, the solution

If the socket binding address in python is in use, an error will often occur,

Under Linux:


            It will say" socket.error: [Errno 98] Address already in use "

Under the Windows:

          Is displayed " socket.error: [Errno 10048] Normally each socket address (protocol) / The network address / Port) can only be used once

This is because socket does not support address reuse by default, if the need to reuse the display Settings, that is, before the binding call setsockop function t socket to allow address reuse: socket.setsockopt(socket.sol_socket, socket.so_reuseaddr,1)

Such as:


        self.recSocket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) 
        self.recSocket.settimeout(CHECK_TIMEOUT)
        self.recSocket.setsockopt(socket.SOL_SOCKET,socket.SO_REUSEADDR,1) 
        self.recSocket.bind(('', UDP_PORT)) 


Related articles: